package gold.digger;

import gold.utils.InputUtil;

import java.util.Arrays;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC948 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int bagOfTokensScore(int[] tokens, int power) {
            if (tokens.length <= 0) return 0;
            if (tokens.length == 1) return tokens[0] <= power ? 1 : 0;
            Arrays.sort(tokens);
            int maxScore = 0, score = 0, i = 0, j = tokens.length - 1;
            while (i < j) {
                if (power < tokens[i]) break;
                while (power >= tokens[i]) {
                    power -= tokens[i++];
                    ++score;// 疯狂收割分数
                }

                maxScore = Math.max(maxScore, score);

                if (i >= j) break;
                if (score > 0) {
                    power += tokens[j--];
                    score--;
                }
            }

            return maxScore;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.bagOfTokensScore(InputUtil.toIntegerArray("[100]"), 50));
        System.out.println(solution.bagOfTokensScore(InputUtil.toIntegerArray("[100,200]"), 150));
        System.out.println(solution.bagOfTokensScore(InputUtil.toIntegerArray("[100,200,300,400]"), 200));
        System.out.println(solution.bagOfTokensScore(InputUtil.toIntegerArray("[6,0,39,52,45,49,59,68,42,37]"), 99));
    }

    public static void main(String[] args) throws Exception {
        LC948 an = new LC948();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
